package cn.edu.sjtu.process_management.controller;

import cn.edu.sjtu.process_management.model.Result;
import cn.edu.sjtu.process_management.model.Role;
import cn.edu.sjtu.process_management.service.HistoryService;
import cn.edu.sjtu.process_management.util.JWTUtil;
import cn.edu.sjtu.process_management.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author loumoon
 * @date 2019-12-13 15:14
 */
@RestController
public class HistoryController {
    @Autowired
    private HistoryService historyService;

    /*查找流程运行记录*/
    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public Result findHistories(@RequestHeader("Authorization") String token) {
        String owner = JWTUtil.decodeUserId(token);
        Integer role = JWTUtil.decodeRole(token);

        if (role == Role.MANAGER.ordinal()) { // 对管理人员返回所有流程运行记录
            return ResultUtil.success(historyService.findAllHistories());
        } else { // 对流程人员返回其创建的流程运行记录
            return ResultUtil.success(historyService.findCreatedHistories(owner));
        }
    }

    /*查找流程运行状态*/
    @RequestMapping(value = "/history/status", method = RequestMethod.GET)
    public Result findHistoryStatus(@RequestHeader("Authorization") String token, @RequestParam String historyId) {
        String owner = JWTUtil.decodeUserId(token);
        Integer role = JWTUtil.decodeRole(token);

        if (role == Role.MANAGER.ordinal()) {
            return ResultUtil.success(historyService.findHistoryStatus(historyId));
        } else {
            return ResultUtil.success(historyService.findHistoryStatus(historyId, owner));
        }
    }

    /*查找流程运行中task的返回数据*/
    @RequestMapping(value = "/history/task", method = RequestMethod.GET)
    public Result findHistoryTask(@RequestHeader("Authorization") String token, @RequestParam String historyId, @RequestParam String taskId) {
        String owner = JWTUtil.decodeUserId(token);
        Integer role = JWTUtil.decodeRole(token);

        if (role == Role.MANAGER.ordinal()) {
            return ResultUtil.success(historyService.findHistoryTask(historyId, taskId));
        } else {
            return ResultUtil.success(historyService.findHistoryTask(historyId, taskId, owner));
        }
    }
}
